<?php
namespace common\models;

use Yii;
use yii\base\Model;
use yii\helpers\Json;
use linslin\yii2\curl\Curl;
use common\models\ARCoinType;
use api\modules\v1\models\Assets;
use common\models\ARCoinRecharge;
use common\models\ARCoinWalletCount;
use common\helpers\ExtendFunction;
use api\components\OperateException;

/**
 * 代币钱包模型
 * @author CGA
 */
class CoinWallet extends Model
{
    /**
     * 获取安全加密码
     */
    protected static function getSecurity($params, $addtime, $salt)
    {
        $params['salt'] = md5($salt);
        ksort($params);
        $str = ExtendFunction::array2str($params, '&') . $addtime;
        return strtoupper(md5($str));
    }

    /**
     * 获取资产安全码
     * @param Object $row 数据记录
     */
    public static function getRechargeSecufity($row)
    {
        $slat = Yii::$app->params['salt']['recharge'];
        $param = [
            'uid'    => $row->uid,
            'coin'   => $row->coin,
            'amount' => floatval($row->amount),
            'status' => $row->status,
        ];
        $addtime = $row->security_at;
        $code = self::getSecurity($param, $addtime, $slat);
        return $code;
    }

    /**
     * 校验资产安全码
     * @param Object $row 数据记录
     */
    public static function verifyRechargeSecufity($row)
    {
        $code = self::getRechargeSecufity($row);
        if ($code === $row->security_code) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 发送钱包请求
     * @author CGA
     *
     * @param string $method 请求方法
     * @param array  $param  请求参数
     */
    public static function sendRequst($method, $param)
    {
        $url = Yii::$app->params['coinWallt_info']['api'] . $method;
        $postDate = self::getSign($param);
        $curl = new Curl();
        $curl = $curl->setPostParams($params)
            ->setOption(CURLOPT_TIMEOUT, 5)
            ->setOption(CURLOPT_SSL_VERIFYPEER, false)
            ->setOption(CURLOPT_SSL_VERIFYHOST, false);
        $response = $curl->post($url);
        $result = $response ? Json::decode($$response, true) : [];
        if (!isset($result) || $result['errcode'] !== 0) {
            throw new OperateException('100043');
        } else {
            unset($result['errcode']);
            return $result;
        }
    }

    /**
     * 获取钱包签名
     * @author CGA
     *
     * @param string $method 请求方法
     * @param array  $param  请求参数
     */
    public static function getSign($param)
    {
        $dataJson = Json::encode($param);
        $timestamp = Yii::$app->formatter->asTimestamp('now');
        $signature = sha1($dataJson . $timestamp . Yii::$app->params['coinWallt_info']['apikey']);
        $param['timestamp'] = $timestamp;
        $param['signature'] = $signature;
        return $param;
    }

    /**
     * 添加充值记录
     * @param number $uid    用户编号
     * @param number $coin   货币
     * @param number $amount 数额
     */
    public static function AddRecord($uid, $coin, $amount)
    {
        $row = new ARCoinRecharge();
        $row->uid = $uid;
        $row->coin = $coin;
        $row->amount = $amount;
        $row->status = ARCoinRecharge::STATUS_WAITING;
        $row->security_at = Yii::$app->formatter->asTimestamp('now');
        $row->security_code = self::getRechargeSecufity($row);
        if (!$row->save()) {
            echo "\n\r", "Add Fail!", "\n\r";
        } else {
            echo "\n\r", "Add Success!", "\n\r";
        }
    }

    /**
     * 充值
     */
    public static function recharge()
    {
        $alignment = ARCoinRecharge::find()->where(['status' => ARCoinRecharge::STATUS_WAITING])->all();
        if ($alignment) {
            foreach ($alignment as $row) {
                $transaction = Yii::$app->db->beginTransaction();
                try {
                    $flag = Assets::into($row->uid, $row->coin, $row->amount);
                    if ($flag) {
                        $row->status = ARCoinRecharge::STATUS_SUCCESS;
                        $row->save();
                        $transaction->commit();
                        echo "{$row->id} success", "\r\n";
                    }
                } catch (\Exception $e) {
                    $transaction->rollBack();
                    $row->status = ARCoinRecharge::STATUS_FAIL;
                    $row->save();
                    echo "{$row->id} fail", "\r\n";
                }
            }
        } else {
            echo "0 row fished", "\r\n";
        }
    }

    /**
     * 生成钱包新入币地址
     * @param number $coin 币种
     */
    public static function getNewAddress($coin)
    {
        $type = ARCoinType::find()->where(['id' => $coin])->one();
        $param = [
            'cointype' => $type->name,
        ];
        // $result = self::sendRequst('posturl', $param);
        $result = [
            'address' => '5842k2alm8dteyl1znHL8Da1fLQ1TP14VqF3opWcwv9hjRgHdo5WEgsciiOeQKV7',
        ];
        if ($result) {
            return $result['address'];
        }
    }

    /**
     * 获取交易流水
     */
    public static function getDealflow()
    {
        $ARCoinTypes = ARCoinType::find()->select(['name'])->where(['status' => ARCoinType::STATUS_ACTIVE])->asArray()->column();
        // foreach ($ARCoinType as $coin) {
        $count_max = ARCoinWalletCount::find()->max('endth');
        if (!$count_max) {
            $count_max = 0;
        }
        $param = [
            'starth'   => $count_max + 1,
            'endth'    => $count_max + 1000,
            'cointype' => 'BTC',
        ];

        $result = self::sendRequst('posturl', $param);
        if ($result) {

        } else {
            echo "fail";
        }
        //}
    }

    /**
     * 提币
     */
    public static function coinTakeOut()
    {

    }
}
